<template>
  <div class="lecture-mgr">
    <!-- 页面头部 -->
    <div class="header">
      <h1 class="title">
        <i class="fas fa-cogs"></i>
        教案管理系统
      </h1>
      <p class="subtitle">管理章节和教案文件，仅限管理员访问</p>
    </div>

    <!-- 功能导航 -->
    <div class="nav-tabs">
      <button 
        v-for="tab in tabs" 
        :key="tab.key"
        :class="['tab-btn', { active: activeTab === tab.key }]"
        @click="activeTab = tab.key"
      >
        <i :class="tab.icon"></i>
        {{ tab.label }}
      </button>
    </div>

    <!-- 章节管理 -->
    <div v-if="activeTab === 'chapters'" class="tab-content">
      <div class="section-header">
        <h2>章节管理</h2>
        <button class="btn btn-primary" @click="showAddChapterModal = true">
          <i class="fas fa-plus"></i>
          添加章节
        </button>
      </div>

      <div class="chapters-grid">
        <div 
          v-for="chapter in chapters" 
          :key="chapter.id"
          class="chapter-card"
        >
          <div class="chapter-header">
            <h3>{{ chapter.title }}</h3>
            <div class="chapter-actions">
              <button class="btn btn-sm btn-secondary" @click="editChapter(chapter)">
                <i class="fas fa-edit"></i>
              </button>
              <button class="btn btn-sm btn-danger" @click="deleteChapter(chapter.id)">
                <i class="fas fa-trash"></i>
              </button>
            </div>
          </div>
          <div class="chapter-info">
            <p><strong>ID:</strong> {{ chapter.id }}</p>
            <p><strong>排序:</strong> {{ chapter.sort_order }}</p>
            <p><strong>教案数量:</strong> {{ chapter.lectures?.length || 0 }}</p>
            <p><strong>状态:</strong> 
              <span :class="['status', chapter.status ? 'active' : 'inactive']">
                {{ chapter.status ? '启用' : '禁用' }}
              </span>
            </p>
          </div>
        </div>
      </div>
    </div>

    <!-- 文件上传 -->
    <div v-if="activeTab === 'upload'" class="tab-content">
      <div class="section-header">
        <h2>文件上传</h2>
      </div>

      <div class="upload-section">
        <div class="upload-form">
          <div class="form-group">
            <label>选择章节:</label>
            <select v-model="uploadForm.chapterId" class="form-control">
              <option value="">请选择章节</option>
              <option v-for="chapter in chapters" :key="chapter.id" :value="chapter.id">
                {{ chapter.title }}
              </option>
            </select>
          </div>

          <div class="form-group">
            <label>文件类型:</label>
            <select v-model="uploadForm.fileType" class="form-control">
              <option value="">请选择文件类型</option>
              <option value="pdf">PDF文档</option>
              <option value="md">Markdown文档</option>
              <option value="doc">Word文档(.doc)</option>
              <option value="docx">Word文档(.docx)</option>
              <option value="ppt">PowerPoint(.ppt)</option>
              <option value="pptx">PowerPoint(.pptx)</option>
              <option value="other">其他</option>
            </select>
          </div>

          <div class="form-group">
            <label>章节标题:</label>
            <input 
              v-model="uploadForm.title" 
              type="text" 
              class="form-control" 
              placeholder="请输入章节标题"
            >
          </div>

          <div class="form-group">
            <label>排序顺序:</label>
            <input 
              v-model.number="uploadForm.sortOrder" 
              type="number" 
              class="form-control" 
              placeholder="排序顺序（数字）"
            >
          </div>

          <div class="form-group">
            <label>选择文件:</label>
            <input 
              ref="fileInput"
              type="file" 
              class="form-control" 
              @change="handleFileSelect"
              accept=".pdf,.md,.doc,.docx,.ppt,.pptx"
            >
          </div>

          <div v-if="selectedFile" class="file-preview">
            <h4>文件预览:</h4>
            <div class="file-info">
              <p><strong>文件名:</strong> {{ selectedFile.name }}</p>
              <p><strong>文件大小:</strong> {{ formatFileSize(selectedFile.size) }}</p>
              <p><strong>文件类型:</strong> {{ selectedFile.type }}</p>
            </div>
          </div>

          <div class="form-actions">
            <button 
              class="btn btn-primary" 
              @click="uploadFile"
              :disabled="!canUpload || uploading"
            >
              <i class="fas fa-upload"></i>
              {{ uploading ? '上传中...' : '上传文件' }}
            </button>
            <button class="btn btn-secondary" @click="resetUploadForm">
              <i class="fas fa-undo"></i>
              重置
            </button>
          </div>
        </div>

        <!-- 上传进度 -->
        <div v-if="uploading" class="upload-progress">
          <div class="progress-bar">
            <div class="progress-fill" :style="{ width: uploadProgress + '%' }"></div>
          </div>
          <p>上传进度: {{ uploadProgress }}%</p>
        </div>
      </div>
    </div>

    <!-- 教案管理 -->
    <div v-if="activeTab === 'lectures'" class="tab-content">
      <div class="section-header">
        <h2>教案管理</h2>
        <div class="search-box">
          <input 
            v-model="searchQuery" 
            type="text" 
            placeholder="搜索教案..."
            class="form-control"
          >
          <i class="fas fa-search"></i>
        </div>
      </div>

      <div class="lectures-table">
        <table class="table">
          <thead>
            <tr>
              <th>ID</th>
              <th>标题</th>
              <th>文件名</th>
              <th>章节</th>
              <th>类型</th>
              <th>大小</th>
              <th>排序</th>
              <th>状态</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="lecture in filteredLectures" :key="lecture.id">
              <td>{{ lecture.id }}</td>
              <td>{{ lecture.title }}</td>
              <td>{{ lecture.name }}</td>
              <td>{{ getChapterTitle(lecture.chapter_id) }}</td>
              <td>
                <span :class="['file-type', lecture.file_type]">
                  {{ lecture.file_type.toUpperCase() }}
                </span>
              </td>
              <td>{{ formatFileSize(lecture.file_size) }}</td>
              <td>{{ lecture.sort_order }}</td>
              <td>
                <span :class="['status', lecture.status ? 'active' : 'inactive']">
                  {{ lecture.status ? '启用' : '禁用' }}
                </span>
              </td>
              <td>
                <div class="action-buttons">
                  <button class="btn btn-sm btn-info" @click="previewLectureHandler(lecture)">
                    <i class="fas fa-eye"></i>
                  </button>
                  <button class="btn btn-sm btn-secondary" @click="editLecture(lecture)">
                    <i class="fas fa-edit"></i>
                  </button>
                  <button class="btn btn-sm btn-danger" @click="deleteLecture(lecture.id)">
                    <i class="fas fa-trash"></i>
                  </button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 添加章节模态框 -->
    <div v-if="showAddChapterModal" class="modal-overlay" @click="closeModal">
      <div class="modal" @click.stop>
        <div class="modal-header">
          <h3>{{ editingChapter ? '编辑章节' : '添加章节' }}</h3>
          <button class="close-btn" @click="closeModal">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>章节ID:</label>
            <input 
              v-model="chapterForm.id" 
              type="text" 
              class="form-control" 
              placeholder="如: chap01"
              :disabled="!!editingChapter"
            >
          </div>
          <div class="form-group">
            <label>章节标题:</label>
            <input 
              v-model="chapterForm.title" 
              type="text" 
              class="form-control" 
              placeholder="如: 第1次课"
            >
          </div>
          <div class="form-group">
            <label>排序顺序:</label>
            <input 
              v-model.number="chapterForm.sortOrder" 
              type="number" 
              class="form-control" 
              placeholder="排序顺序"
            >
          </div>
          <div class="form-group">
            <label>
              <input 
                v-model="chapterForm.status" 
                type="checkbox"
              >
              启用章节
            </label>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="closeModal">取消</button>
          <button class="btn btn-primary" @click="saveChapter">
            {{ editingChapter ? '更新' : '创建' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 编辑教案模态框 -->
    <div v-if="showEditLectureModal" class="modal-overlay" @click="closeModal">
      <div class="modal" @click.stop>
        <div class="modal-header">
          <h3>编辑教案</h3>
          <button class="close-btn" @click="closeModal">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>教案标题:</label>
            <input 
              v-model="lectureForm.title" 
              type="text" 
              class="form-control"
            >
          </div>
          <div class="form-group">
            <label>文件名:</label>
            <input 
              v-model="lectureForm.name" 
              type="text" 
              class="form-control"
            >
          </div>
          <div class="form-group">
            <label>所属章节:</label>
            <select v-model="lectureForm.chapterId" class="form-control">
              <option v-for="chapter in chapters" :key="chapter.id" :value="chapter.id">
                {{ chapter.title }}
              </option>
            </select>
          </div>
          <div class="form-group">
            <label>文件类型:</label>
            <select v-model="lectureForm.fileType" class="form-control">
              <option value="pdf">PDF</option>
              <option value="md">Markdown</option>
              <option value="doc">Word(.doc)</option>
              <option value="docx">Word(.docx)</option>
              <option value="ppt">PowerPoint(.ppt)</option>
              <option value="pptx">PowerPoint(.pptx)</option>
              <option value="other">其他</option>
            </select>
          </div>
          <div class="form-group">
            <label>排序顺序:</label>
            <input 
              v-model.number="lectureForm.sortOrder" 
              type="number" 
              class="form-control"
            >
          </div>
          <div class="form-group">
            <label>
              <input 
                v-model="lectureForm.status" 
                type="checkbox"
              >
              启用
            </label>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="closeModal">取消</button>
          <button class="btn btn-primary" @click="saveLecture">更新</button>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      <i class="fas fa-spinner fa-spin"></i>
      加载中...
    </div>

    <!-- Markdown预览模态框 -->
    <MarkdownModal 
      :visible="showPreviewModal"
      :file-path="previewLecture?.path"
      :title="previewLecture?.title || '教案预览'"
      :file-type="previewLecture?.file_type"
      @close="closePreviewModal"
    />

    <!-- 消息提示 -->
    <div v-if="message" :class="['message', messageType]">
      <i :class="messageType === 'success' ? 'fas fa-check' : 'fas fa-exclamation-triangle'"></i>
      {{ message }}
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { useRouter } from 'vue-router'
import MarkdownModal from '@/components/MarkdownModal.vue'

// 类型定义
interface Chapter {
  id: string
  title: string
  sort_order: number
  status: number
  lectures?: Lecture[]
}

interface Lecture {
  id: number
  chapter_id: string
  name: string
  title: string
  path: string
  file_type: string
  file_size: number
  sort_order: number
  status: number
}

// 组合式API
const authStore = useAuthStore()
const router = useRouter()

// 检查管理员权限
if (!authStore.isAdmin) {
  router.push('/login')
}

// 响应式数据
const activeTab = ref('chapters')
const loading = ref(false)
const message = ref('')
const messageType = ref<'success' | 'error'>('success')
const chapters = ref<Chapter[]>([])
const lectures = ref<Lecture[]>([])
const searchQuery = ref('')

// 模态框状态
const showAddChapterModal = ref(false)
const showEditLectureModal = ref(false)
const showPreviewModal = ref(false)
const editingChapter = ref<Chapter | null>(null)
const editingLecture = ref<Lecture | null>(null)

// 预览相关
const previewLecture = ref<Lecture | null>(null)

// 文件上传相关
const selectedFile = ref<File | null>(null)
const uploading = ref(false)
const uploadProgress = ref(0)
const fileInput = ref<HTMLInputElement | null>(null)

// 表单数据
const uploadForm = ref({
  chapterId: '',
  fileType: '',
  title: '',
  sortOrder: 1
})

const chapterForm = ref({
  id: '',
  title: '',
  sortOrder: 1,
  status: true
})

const lectureForm = ref({
  id: 0,
  chapterId: '',
  name: '',
  title: '',
  fileType: '',
  sortOrder: 1,
  status: true
})

// 标签页配置
const tabs = [
  { key: 'chapters', label: '章节管理', icon: 'fas fa-book' },
  { key: 'upload', label: '文件上传', icon: 'fas fa-upload' },
  { key: 'lectures', label: '教案管理', icon: 'fas fa-file-alt' }
]

// API基础URL
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || '/api'

// 计算属性
const canUpload = computed(() => {
  return uploadForm.value.chapterId && 
         uploadForm.value.fileType && 
         uploadForm.value.title && 
         selectedFile.value
})

const filteredLectures = computed(() => {
  if (!searchQuery.value) return lectures.value
  const query = searchQuery.value.toLowerCase()
  return lectures.value.filter(lecture => 
    lecture.title.toLowerCase().includes(query) ||
    lecture.name.toLowerCase().includes(query)
  )
})

// 方法
const showMessage = (msg: string, type: 'success' | 'error' = 'success') => {
  message.value = msg
  messageType.value = type
  setTimeout(() => {
    message.value = ''
  }, 3000)
}

const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const getChapterTitle = (chapterId: string): string => {
  const chapter = chapters.value.find(c => c.id === chapterId)
  return chapter ? chapter.title : chapterId
}

// API调用方法
const fetchChapters = async () => {
  try {
    loading.value = true
    const response = await fetch(`${API_BASE_URL}/lectures/chapters`, {
    headers: {
      'Authorization': `Bearer ${authStore.token}`
    }
  })
    
    if (!response.ok) {
      throw new Error('获取章节列表失败')
    }
    
    const data = await response.json()
    if (data.success) {
      chapters.value = data.data
    } else {
      throw new Error(data.message || '获取章节列表失败')
    }
  } catch (error) {
    console.error('获取章节列表失败:', error)
    showMessage('获取章节列表失败', 'error')
  } finally {
    loading.value = false
  }
}

const fetchLectures = async () => {
  try {
    loading.value = true
    const response = await fetch(`${API_BASE_URL}/lectures`, {
      headers: {
        'Authorization': `Bearer ${authStore.token}`
      }
    })
    
    if (!response.ok) {
      throw new Error('获取教案列表失败')
    }
    
    const data = await response.json()
    if (data.success) {
      lectures.value = data.data
    } else {
      throw new Error(data.message || '获取教案列表失败')
    }
  } catch (error) {
    console.error('获取教案列表失败:', error)
    showMessage('获取教案列表失败', 'error')
  } finally {
    loading.value = false
  }
}

// 文件处理
const handleFileSelect = (event: Event) => {
  const target = event.target as HTMLInputElement
  if (target.files && target.files.length > 0) {
    selectedFile.value = target.files[0]
    
    // 自动设置文件类型
    const fileName = selectedFile.value.name
    const extension = fileName.split('.').pop()?.toLowerCase()
    if (extension) {
      const typeMap: Record<string, string> = {
        'pdf': 'pdf',
        'md': 'md',
        'doc': 'doc',
        'docx': 'docx',
        'ppt': 'ppt',
        'pptx': 'pptx'
      }
      uploadForm.value.fileType = typeMap[extension] || 'other'
    }
    
    // 自动设置标题（去掉扩展名）
    if (!uploadForm.value.title) {
      uploadForm.value.title = fileName.replace(/\.[^/.]+$/, '')
    }
  }
}

const uploadFile = async () => {
  if (!canUpload.value) return
  
  try {
    uploading.value = true
    uploadProgress.value = 0
    
    const formData = new FormData()
    formData.append('file', selectedFile.value!)
    formData.append('chapterNumber', uploadForm.value.chapterId.replace('chap', ''))
    formData.append('materialType', 'lecture')
    
    // 先上传文件
    const uploadResponse = await fetch(`${API_BASE_URL}/file/upload`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${authStore.token}`
      },
      body: formData
    })
    
    uploadProgress.value = 50
    
    if (!uploadResponse.ok) {
      throw new Error('文件上传失败')
    }
    
    const uploadData = await uploadResponse.json()
    console.log('上传响应数据:', uploadData)
    if (!uploadData.success) {
      throw new Error(uploadData.message || '文件上传失败')
    }
    
    uploadProgress.value = 75
    
    // 创建教案记录
    const lectureData = {
      chapter_id: uploadForm.value.chapterId,
      name: selectedFile.value!.name,
      title: uploadForm.value.title,
      path: uploadData.data.url.replace('/public', ''),
      file_type: uploadForm.value.fileType,
      file_size: selectedFile.value!.size,
      sort_order: uploadForm.value.sortOrder
    }
    
    console.log('准备提交的教案数据:', lectureData)
    
    const lectureResponse = await fetch(`${API_BASE_URL}/lectures`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${authStore.token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(lectureData)
    })
    
    if (!lectureResponse.ok) {
      throw new Error('创建教案记录失败')
    }
    
    const lectureResult = await lectureResponse.json()
    if (!lectureResult.success) {
      throw new Error(lectureResult.message || '创建教案记录失败')
    }
    
    uploadProgress.value = 100
    
    showMessage('文件上传并创建教案成功！')
    resetUploadForm()
    await fetchLectures() // 刷新教案列表
    
  } catch (error) {
    console.error('上传失败:', error)
    showMessage(error instanceof Error ? error.message : '上传失败', 'error')
  } finally {
    uploading.value = false
    uploadProgress.value = 0
  }
}

const resetUploadForm = () => {
  uploadForm.value = {
    chapterId: '',
    fileType: '',
    title: '',
    sortOrder: 1
  }
  selectedFile.value = null
  if (fileInput.value) {
    fileInput.value.value = ''
  }
}

// 章节管理
const editChapter = (chapter: Chapter) => {
  editingChapter.value = chapter
  chapterForm.value = {
    id: chapter.id,
    title: chapter.title,
    sortOrder: chapter.sort_order,
    status: !!chapter.status
  }
  showAddChapterModal.value = true
}

const deleteChapter = async (chapterId: string) => {
  if (!confirm('确定要删除这个章节吗？这将同时删除该章节下的所有教案。')) {
    return
  }
  
  try {
    const response = await fetch(`${API_BASE_URL}/lectures/chapters/${chapterId}`, {
    method: 'DELETE',
    headers: {
      'Authorization': `Bearer ${authStore.token}`
    }
  })
    
    if (!response.ok) {
      throw new Error('删除章节失败')
    }
    
    const data = await response.json()
    if (data.success) {
      showMessage('章节删除成功')
      await fetchChapters()
      await fetchLectures()
    } else {
      throw new Error(data.message || '删除章节失败')
    }
  } catch (error) {
    console.error('删除章节失败:', error)
    showMessage(error instanceof Error ? error.message : '删除章节失败', 'error')
  }
}

const saveChapter = async () => {
  try {
    const chapterData = {
      id: chapterForm.value.id,
      title: chapterForm.value.title,
      sort_order: chapterForm.value.sortOrder,
      status: chapterForm.value.status ? 1 : 0
    }
    
    let response
    if (editingChapter.value) {
      // 更新章节
      response = await fetch(`${API_BASE_URL}/lectures/chapters/${editingChapter.value.id}`, {
        method: 'PUT',
        headers: {
          'Authorization': `Bearer ${authStore.token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(chapterData)
      })
    } else {
      // 创建章节
      response = await fetch(`${API_BASE_URL}/lectures/chapters`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${authStore.token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(chapterData)
      })
    }
    
    if (!response.ok) {
      throw new Error(editingChapter.value ? '更新章节失败' : '创建章节失败')
    }
    
    const data = await response.json()
    if (data.success) {
      showMessage(editingChapter.value ? '章节更新成功' : '章节创建成功')
      closeModal()
      await fetchChapters()
    } else {
      throw new Error(data.message || (editingChapter.value ? '更新章节失败' : '创建章节失败'))
    }
  } catch (error) {
    console.error('保存章节失败:', error)
    showMessage(error instanceof Error ? error.message : '保存章节失败', 'error')
  }
}

// 教案管理
const previewLectureHandler = (lecture: Lecture) => {
  previewLecture.value = lecture
  showPreviewModal.value = true
}

const closePreviewModal = () => {
  showPreviewModal.value = false
  previewLecture.value = null
}

const editLecture = (lecture: Lecture) => {
  editingLecture.value = lecture
  lectureForm.value = {
    id: lecture.id,
    chapterId: lecture.chapter_id,
    name: lecture.name,
    title: lecture.title,
    fileType: lecture.file_type,
    sortOrder: lecture.sort_order,
    status: !!lecture.status
  }
  showEditLectureModal.value = true
}

const deleteLecture = async (lectureId: number) => {
  if (!confirm('确定要删除这个教案吗？')) {
    return
  }
  
  try {
    const response = await fetch(`${API_BASE_URL}/lectures/${lectureId}`, {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${authStore.token}`
      }
    })
    
    if (!response.ok) {
      throw new Error('删除教案失败')
    }
    
    const data = await response.json()
    if (data.success) {
      showMessage('教案删除成功')
      await fetchLectures()
    } else {
      throw new Error(data.message || '删除教案失败')
    }
  } catch (error) {
    console.error('删除教案失败:', error)
    showMessage(error instanceof Error ? error.message : '删除教案失败', 'error')
  }
}

const saveLecture = async () => {
  try {
    const lectureData = {
      chapter_id: lectureForm.value.chapterId,
      name: lectureForm.value.name,
      title: lectureForm.value.title,
      file_type: lectureForm.value.fileType,
      sort_order: lectureForm.value.sortOrder,
      status: lectureForm.value.status ? 1 : 0
    }
    
    const response = await fetch(`${API_BASE_URL}/lectures/${lectureForm.value.id}`, {
      method: 'PUT',
      headers: {
        'Authorization': `Bearer ${authStore.token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(lectureData)
    })
    
    if (!response.ok) {
      throw new Error('更新教案失败')
    }
    
    const data = await response.json()
    if (data.success) {
      showMessage('教案更新成功')
      closeModal()
      await fetchLectures()
    } else {
      throw new Error(data.message || '更新教案失败')
    }
  } catch (error) {
    console.error('更新教案失败:', error)
    showMessage(error instanceof Error ? error.message : '更新教案失败', 'error')
  }
}

// 模态框管理
const closeModal = () => {
  showAddChapterModal.value = false
  showEditLectureModal.value = false
  showPreviewModal.value = false
  editingChapter.value = null
  editingLecture.value = null
  previewLecture.value = null
  chapterForm.value = {
    id: '',
    title: '',
    sortOrder: 1,
    status: true
  }
  lectureForm.value = {
    id: 0,
    chapterId: '',
    name: '',
    title: '',
    fileType: '',
    sortOrder: 1,
    status: true
  }
}

// 生命周期
onMounted(async () => {
  await fetchChapters()
  await fetchLectures()
})
</script>

<style scoped>
.lecture-mgr {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.header {
  text-align: center;
  margin-bottom: 20px;
  padding: 15px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 10px;
}

.title {
  font-size: 1.8rem;
  margin: 0 0 5px 0;
  font-weight: 600;
}

.subtitle {
  font-size: 0.95rem;
  margin: 0;
  opacity: 0.9;
}

.nav-tabs {
  display: flex;
  gap: 10px;
  margin-bottom: 30px;
  border-bottom: 2px solid #e1e5e9;
}

.tab-btn {
  padding: 12px 24px;
  border: none;
  background: none;
  cursor: pointer;
  font-size: 1rem;
  color: #6c757d;
  border-bottom: 3px solid transparent;
  transition: all 0.3s ease;
}

.tab-btn:hover {
  color: #495057;
  background-color: #f8f9fa;
}

.tab-btn.active {
  color: #007bff;
  border-bottom-color: #007bff;
  background-color: #f8f9fa;
}

.tab-btn i {
  margin-right: 8px;
}

.tab-content {
  min-height: 500px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #dee2e6;
}

.section-header h2 {
  margin: 0;
  color: #495057;
}

.search-box {
  position: relative;
  width: 300px;
}

.search-box input {
  width: 100%;
  padding-right: 40px;
}

.search-box i {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #6c757d;
}

.chapters-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.chapter-card {
  border: 1px solid #dee2e6;
  border-radius: 8px;
  padding: 20px;
  background: white;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.chapter-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0,0,0,0.15);
}

.chapter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.chapter-header h3 {
  margin: 0;
  color: #495057;
}

.chapter-actions {
  display: flex;
  gap: 5px;
}

.chapter-info p {
  margin: 8px 0;
  color: #6c757d;
}

.upload-section {
  max-width: 600px;
  margin: 0 auto;
}

.upload-form {
  background: white;
  padding: 30px;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
  color: #495057;
}

.form-control {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #ced4da;
  border-radius: 5px;
  font-size: 1rem;
  transition: border-color 0.3s ease, box-shadow 0.3s ease;
}

.form-control:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 0.2rem rgba(0,123,255,0.25);
}

.file-preview {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 5px;
  margin-top: 10px;
}

.file-preview h4 {
  margin: 0 0 10px 0;
  color: #495057;
}

.file-info p {
  margin: 5px 0;
  color: #6c757d;
}

.form-actions {
  display: flex;
  gap: 10px;
  margin-top: 20px;
}

.upload-progress {
  margin-top: 20px;
  text-align: center;
}

.progress-bar {
  width: 100%;
  height: 20px;
  background-color: #e9ecef;
  border-radius: 10px;
  overflow: hidden;
  margin-bottom: 10px;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #007bff, #0056b3);
  transition: width 0.3s ease;
}

.lectures-table {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.table {
  width: 100%;
  border-collapse: collapse;
}

.table th,
.table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #dee2e6;
}

.table th {
  background-color: #f8f9fa;
  font-weight: 600;
  color: #495057;
}

.table tbody tr:hover {
  background-color: #f8f9fa;
}

.file-type {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.8rem;
  font-weight: 500;
  text-transform: uppercase;
}

.file-type.pdf {
  background-color: #dc3545;
  color: white;
}

.file-type.md {
  background-color: #6f42c1;
  color: white;
}

.file-type.doc,
.file-type.docx {
  background-color: #007bff;
  color: white;
}

.file-type.ppt,
.file-type.pptx {
  background-color: #fd7e14;
  color: white;
}

.file-type.other {
  background-color: #6c757d;
  color: white;
}

.status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.8rem;
  font-weight: 500;
}

.status.active {
  background-color: #28a745;
  color: white;
}

.status.inactive {
  background-color: #dc3545;
  color: white;
}

.action-buttons {
  display: flex;
  gap: 5px;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 0.9rem;
  font-weight: 500;
  text-decoration: none;
  display: inline-flex;
  align-items: center;
  gap: 5px;
  transition: all 0.3s ease;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-primary {
  background-color: #007bff;
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background-color: #0056b3;
}

.btn-secondary {
  background-color: #6c757d;
  color: white;
}

.btn-secondary:hover {
  background-color: #545b62;
}

.btn-danger {
  background-color: #dc3545;
  color: white;
}

.btn-danger:hover {
  background-color: #c82333;
}

.btn-info {
  background-color: #17a2b8;
  color: white;
}

.btn-info:hover {
  background-color: #138496;
}

.btn-sm {
  padding: 4px 8px;
  font-size: 0.8rem;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal {
  background: white;
  border-radius: 10px;
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 10px 30px rgba(0,0,0,0.3);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #dee2e6;
}

.modal-header h3 {
  margin: 0;
  color: #495057;
}

.close-btn {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: #6c757d;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  color: #495057;
}

.modal-body {
  padding: 20px;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 20px;
  border-top: 1px solid #dee2e6;
}

.loading {
  text-align: center;
  padding: 40px;
  color: #6c757d;
  font-size: 1.1rem;
}

.loading i {
  font-size: 2rem;
  margin-bottom: 10px;
  display: block;
}

.message {
  position: fixed;
  top: 20px;
  right: 20px;
  padding: 15px 20px;
  border-radius: 5px;
  color: white;
  font-weight: 500;
  z-index: 1001;
  display: flex;
  align-items: center;
  gap: 10px;
  min-width: 300px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}

.message.success {
  background-color: #28a745;
}

.message.error {
  background-color: #dc3545;
}

@media (max-width: 768px) {
  .lecture-mgr {
    padding: 10px;
  }
  
  .title {
    font-size: 1.5rem;
  }
  
  .nav-tabs {
    flex-direction: column;
  }
  
  .section-header {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .search-box {
    width: 100%;
  }
  
  .chapters-grid {
    grid-template-columns: 1fr;
  }
  
  .form-actions {
    flex-direction: column;
  }
  
  .modal {
    width: 95%;
    margin: 10px;
  }
  
  .table {
    font-size: 0.8rem;
  }
  
  .action-buttons {
    flex-direction: column;
  }
}


</style>